import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 * RUNS ONLY ONCE
 */
public class RO_SplitTrainingData {
	static User[] USER = new User[1000990];
	static User[] USERA = new User[1000990];
	static User[] USERB = new User[1000990];

	static String FILE_PATH = "../track1/trainIdx1.txt" + ".ser";

	public static void main(String[] args) {
		long time;

		time = System.currentTimeMillis();
		readSerialized();
		System.out.println(System.currentTimeMillis() - time);

		time = System.currentTimeMillis();
		split();
		System.out.println(System.currentTimeMillis() - time);

		USER = null;
		System.gc();

		time = System.currentTimeMillis();
		writeSerialisedResult();
		System.out.println(System.currentTimeMillis() - time);
	}

	static void readSerialized() {
		System.out.println("readSerialized: " + FILE_PATH);

		try {
			InputStream file = new FileInputStream(FILE_PATH);
			InputStream buffer = new BufferedInputStream(file);
			ObjectInput input = new ObjectInputStream(buffer);
			try {
				USER = (User[]) input.readObject();
			} finally {
				input.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static void split() {
		System.out.println("split: " + USER[0]);

		for (int u = 0; u < USER.length; u++) {
			int UserCount = USER[u].ilen;
			int countA = UserCount / 2;
			int countB = UserCount - countA;

			USERA[u] = new User(countA);
			USERB[u] = new User(countB);

			int[] i = USER[u].items;
			System.arraycopy(i, 0, USERA[u].items, 0, countA);
			System.arraycopy(i, countA, USERB[u].items, 0, countB);

			byte[] v = USER[u].votes;
			System.arraycopy(v, 0, USERA[u].votes, 0, countA);
			System.arraycopy(v, countA, USERB[u].votes, 0, countB);
		}
	}

	static void writeSerialisedResult() {
		System.out.println("writeSerialisedResult: " + FILE_PATH + "A");

		try {
			OutputStream file = new FileOutputStream(FILE_PATH + "A");
			OutputStream buffer = new BufferedOutputStream(file);
			ObjectOutput output = new ObjectOutputStream(buffer);
			try {
				output.writeObject(USERA);
			} finally {
				output.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("writeSerialisedResult: " + FILE_PATH + "B");

		try {
			OutputStream file = new FileOutputStream(FILE_PATH + "B");
			OutputStream buffer = new BufferedOutputStream(file);
			ObjectOutput output = new ObjectOutputStream(buffer);
			try {
				output.writeObject(USERB);
			} finally {
				output.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
